package com.cy.milktea.config.system;

import com.cy.milktea.utils.SpringContextUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;


import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;

public class MybatisRedisCache implements Cache {

    private RedisTemplate getRedisTemplate() {
        return (RedisTemplate) SpringContextUtils.getBean("redisTemplate");
    }

    /* 唯一标识符cacheId  即namespace */
    private String cacheId;

    public MybatisRedisCache(String cacheId) {
        this.cacheId = cacheId;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return null;
    }

    @Override
    public String getId() {
        return this.cacheId;
    }

    /* 存入缓存 */
    @Override
    public void putObject(Object key, Object value) {
        getRedisTemplate().opsForHash().put(cacheId, key.toString(), value);
        getRedisTemplate().expire(cacheId, randomTime(), TimeUnit.SECONDS);

    }

    /* 基于key获取数据 */
    @Override
    public Object getObject(Object key) {
        return getRedisTemplate().opsForHash().get(cacheId, key.toString());
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }

    /* 清空缓存 */
    @Override
    public void clear() {
        getRedisTemplate().delete(cacheId);
    }

    /* 获取缓存数量 */
    @Override
    public int getSize() {
        return getRedisTemplate().opsForHash().size(cacheId).intValue();
    }

    /* 获取随机时间,防止缓存集中过期 */
    private int randomTime() {
        return new Random().nextInt(100) + 20;
    }
}
